package logic

import (
	"context"
	"fmt"
	"tuan/models/cache"
	"tuan/models/mysql"

	"tuan/tuanrpc/internal/svc"
	"tuan/tuanrpc/tuanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *tuanrpc.LoginRequest) (*tuanrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()
	if result != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}
	s, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
	if s != in.Sendsms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if in.Mobile != "" {
		return nil, fmt.Errorf("手机号不能为空")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请前去注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	return &tuanrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
